package controllers

import (
	"encoding/json"
	"errors"
	"fmt"

	md "gitee.com/countpoison/youbei/models"
)

func (c *MainController) HostAdd() {
	ob := new(md.Host)
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, ob); err != nil {
		c.APIReturn(500, "解析录入失败", err)
	}
	c.APIReturn(500, "录入主机失败", ob.Add())
	c.APIReturn(200, "录入成功", nil)
}

func (c *MainController) HostUpdate() {
	id := c.Ctx.Input.Param(":id")
	ob := new(md.Host)
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, ob); err != nil {
		c.APIReturn(500, "解析修改失败", err)
	}
	ob.ID = id
	c.APIReturn(500, "修改主机失败", ob.Update())
	c.APIReturn(200, "修改成功", nil)
}

func (c *MainController) HostDelete() {
	id := c.Ctx.Input.Param(":id")
	ob := new(md.Host)
	ob.ID = id
	c.APIReturn(500, "删除主机失败", ob.Delete())
	c.APIReturn(200, "删除成功", nil)
}

func (c *MainController) HostsGet() {
	hosts := make([]md.Host, 0)
	err := md.Localdb().Find(&hosts)
	if err != nil {
		fmt.Println(err.Error())
	}
	c.APIReturn(500, "获取数据失败", err)
	c.APIReturn(200, "获取数据成功", hosts)
}

func (c *MainController) HostGet() {
	id := c.Ctx.Input.Param(":id")
	host := new(md.Host)
	host.ID = id
	bol, err := md.Localdb().Get(host)

	c.APIReturn(500, "获取数据失败", err)
	if !bol {
		c.APIReturn(500, "数据不存在", errors.New("数据不存在"))
	}
	c.APIReturn(200, "获取数据成功", host)
}
